package com.suixun.controller.credits;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;

import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import com.authority.controller.BaseManager;
import com.suixun.util.Constant;

/**
 * 图片类
 * 
 * @author yh
 * @date 2017年12月8日
 */
@RestController
@RequestMapping("/file/image")
public class FileImgController extends BaseManager {

    @Value("${file.imgpath}")
    private String imgPath;

    /**
     * 根据id获取图片流
     * 
     * @param response
     * @param id
     * @throws IOException
     */
    @RequestMapping(value = "/get_image", method = RequestMethod.GET)
    public Object getImage(HttpServletResponse response, @RequestParam(value = "name", required = false) String name) {
        try {
            if (StringUtils.isEmpty(name)) {
                return fail(Constant.EXCEPTION.OPERATE_FAIL);
            }
            String filepath = imgPath + File.separator + name;
            String suffix = name.substring(name.lastIndexOf(".") + 1);
            FileInputStream fis = new FileInputStream(filepath);
            int i = fis.available();
            byte data[] = new byte[i];
            fis.read(data);
            fis.close();
            response.setContentType("image/" + suffix);
            OutputStream os = response.getOutputStream();
            os.write(data);
            os.close();
            return success();
        } catch (Exception e) {
            logger("FileImgController getImage:" + e.getMessage(), e);
            return fail(Constant.EXCEPTION.OPERATE_FAIL);
        }
    }

    /**
     * 单图片上传
     * 
     * @param file
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "/img_upload", method = RequestMethod.POST)
    public Object imgUpload(@RequestParam("file") MultipartFile file) {
        /*if (!checkRight()) {
            return fail(Constant.Authority.CHECK_FALSE);
        }*/
        try {
            String name = null;
            if (!file.isEmpty()) {
                String originalName = file.getOriginalFilename();
                String uuid = UUID.randomUUID().toString();
                name = uuid + "." + originalName.substring(originalName.lastIndexOf(".") + 1);
                fileUpload(file, getImgPath() + File.separator + name);
            }
            return success(name);
        } catch (Exception e) {
            logger("FileImgController imgUpload:" + e.getMessage(), e);
            return fail(Constant.EXCEPTION.OPERATE_FAIL);
        }

    }

    /**
     * 多图片上传
     * 
     * @param files
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "/img_uploads", method = RequestMethod.POST)
    public Object imgUploads(@RequestParam("files") MultipartFile[] files) {
        /*if (!checkRight()) {
            return fail(Constant.Authority.CHECK_FALSE);
        }*/
        try {
            List<String> list = new ArrayList<>();
            if (files != null && files.length != 0) {
                for (MultipartFile file : files) {
                    String originalName = file.getOriginalFilename();
                    String uuid = UUID.randomUUID().toString();
                    String name = uuid + "." + originalName.substring(originalName.lastIndexOf(".") + 1);
                    fileUpload(file, getImgPath() + File.separator + name);
                    list.add(name);
                }
            }
            return success(list);
        } catch (Exception e) {
            logger("FileImgController imgUploads:" + e.getMessage(), e);
            return fail(Constant.EXCEPTION.OPERATE_FAIL);
        }

    }

    /**
     * 保存图片
     * 
     * @param mfile
     * @param filePath
     * @throws Exception
     */
    private void fileUpload(MultipartFile mfile, String filePath) throws Exception {
        File file = new File(filePath);
        if (!file.exists()) {
            if (!file.getParentFile().exists()) {
                file.getParentFile().mkdirs();
            }
            file.createNewFile();
        }
        mfile.transferTo(file);
    }

    public String getImgPath() {
        return imgPath;
    }

}
